package com.st.api.interceptor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.st.api.constants.ReturnServiceCode;
import com.st.api.util.DesEncryptionUtils;
import com.st.api.util.EncryptionUtils;
import com.st.api.util.StringUtils;
/**
 * 认证拦截器
 * 拦截除/login/* 以外的所有的url
 * @author gaohao
 *
 */
public class AuthorizeInterceptor implements HandlerInterceptor{

	
	 /**  
     * 在业务处理器处理请求之前被调用  
     * 如果返回false  
     *     从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链 
     * 如果返回true  
     *    执行下一个拦截器,直到所有的拦截器都执行完毕  
     *    再执行被拦截的Controller  
     *    然后进入拦截器链,  
     *    从最后一个拦截器往回执行所有的postHandle()  
     *    接着再从最后一个拦截器往回执行所有的afterCompletion()  
	 * @throws IOException 
     */    
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException
			 {
		//validate uid and token is not null
		if(StringUtils.isNull(request.getParameter("uid"))||
				StringUtils.isNull(request.getParameter("token"))){
			
			Map<String,Object>  errorMap = StringUtils.returnMap(ReturnServiceCode.USERID_OR_TOKEN_NULL, "userid or token is null");
		
			//message out to fe
			response.getWriter().write(StringUtils.mapToJsonStr(errorMap));
			return false;
		}
		
		//String validateToken = EncryptionUtils.MD5Encode(request.getParameter("uid"));
		//String validateToken = new DesEncryptionUtils().getToken(request.getParameter("uid"));
		//validate token
		boolean validateToken = false;
		
		try {
			validateToken = new DesEncryptionUtils().validateToken(request.getParameter("uid"),request.getParameter("token"));
		} catch (Exception e) {
			//e.printStackTrace();
		}
		
		if(!validateToken){
			
			Map<String,Object>  errorMap = StringUtils.returnMap(ReturnServiceCode.INVALID_TOKEN, "interceptor invalid token");
			
			//messageout to fe
			response.getWriter().write(StringUtils.mapToJsonStr(errorMap));
			
			return false;
		}
		return true;
	}

	 /** 
     * 在业务处理器处理请求执行完成后,生成视图之前执行的动作    
     * 可在modelAndView中加入数据，比如当前时间 
     */  
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		//System.out.println("postHandle :: null");
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		//System.out.println("aterCompletion :: null");
		
	}

	
	
}
